<?php
/*

 All rights Reserved, Designed By www.youyacao.com
 @Description:卡密方法页
 @author:成都市一颗优雅草科技有限公司
 @version 优雅草松鼠聚合直播系统
 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
 正版系统查询系统 zhengbancha.youyacao.com

*/
namespace app\admin\controller;

use \think\Db;

class Card extends Base
{
    protected function getCardTitle($num,$usedays=false){
        if($usedays){
            if($num == 7){
                $num = 2;
            }elseif($num == 31){
                $num = 3;
            }elseif($num == 90){
                $num = 4;
            }elseif($num == 365){
                $num = 5;
            }elseif($num > 365){
                $num = 6;
            }
        }
        $cardlist = ["15分钟免费激活码","【1天】体验激活码","【7天】周卡激活码","【31天】月卡激活码","【90天】季卡激活码","【365天】年卡激活码","【永久】终身激活码"];
        return $cardlist[$num];
    }
    public function cardlist(){
        $list = [];
        for($i=1;$i<=6;$i++){
            $price = floatval(Db::name("settings")->where("set_name","card_".$i)->value("set_value"));
            if($price>0){
                $list[] = array('name'=>'card_'.$i,'title'=>$this->getCardTitle($i).number_format($price,2));
            }
        }
        $this->success($list);
    }

    protected function guuid() {

        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

            mt_rand( 0, 0xffff ),

            mt_rand( 0, 0x0fff ) | 0x4000,

            mt_rand( 0, 0x3fff ) | 0x8000,

            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )

        );

    }

    protected function get_card_time($card_name){
        switch ($card_name){
            case "card_1":
                return ['days'=>1,'time'=>86400];
            case "card_2":
                return ['days'=>7,'time'=>86400 * 7];
            case "card_3":
                return ['days'=>31,'time'=>86400 * 31];
            case "card_4":
                return ['days'=>90,'time'=>86400 * 90];
            case "card_5":
                return ['days'=>365,'time'=>86400 * 365];
            case "card_6":
                return ['days'=>365*100,'time'=>86400 * 365 *100];
        }
        return ['days'=>0,'time'=>900];
    }

    public function buy(){
        if(!request()->isPost()) $this->error('请求类型有误');
        $buycard = strtolower(input("buycard"));
        $cardcount = intval(input("cardcount"));
        if(strlen($buycard) == 0) $this->error("请选择一个卡密类型");
        if($cardcount<=0 || $cardcount>100) $this->error("生成数量为大于0且小于100的整数");
        $price = floatval(Db::name("settings")->where("set_name",$buycard)->value("set_value"));
        if($price<=0) $this->error("系统未设置此卡密的购买价格");
        $totalPrice = $price * $cardcount;
        $cardlist = ["card_1"=>"【1天】体验激活码","card_2"=>"【7天】周卡活码","card_3"=>"【31天】月卡激活码","card_1"=>"【90天】季卡激活码","card_5"=>"【365天】年卡激活码","card_6"=>"【永久】终身激活码"];
        $cardTitle = $cardlist[$buycard];
        Db::startTrans();
        try {
            //先生成订单并扣除点数
            $user = Db::name("user")->where("id",$this->user['id'])->find();//使用事务锁查询收款人余额
            $balance = $user['money'] - $totalPrice;
            if($balance<0){
                Db::rollback();
                $this->error("剩余卡密数量不足");
            }
            $orderid = 0;
            if(Db::name("user")->where("id",$user['id'])->setField("money",$balance)){
                $order = array();
                $order['user_id'] = $user['id'];//订单用户
                $order['payuser_id'] = 0;//收款人用户
                $order['order_no'] = date('YmdHis').rand(1000000,9999999);
                $order['need_money'] = $totalPrice;
                $order['payed_money'] = $totalPrice;
                $order['type'] = 0;//0为购买，1为管理员转账，2为代理转账
                $order['info'] = '购买'.$cardTitle.$cardcount.'个';
                $order['create_time'] = time();
                $order['payed_time'] = time();
                if(Db::name("orders")->insert($order)){
                    $orderid = Db::name('orders')->getLastInsID();
                    //创建资金日志
                    $data = array();
                    $data['user_id'] = $user['id'];
                    $data['order_id'] = $orderid;
                    $data['order_no'] = $order['order_no'];
                    $data['payed_money'] = $order['need_money'];
                    $data['info'] = $order['info'];
                    $data['balance_money'] = $balance;
                    $data['type'] = -1;//-1为扣钱，1为加钱
                    $data['create_time'] = time();
                    if(!Db::name("coin_log")->insert($data)){
                        Db::rollback();
                        $this->error("未知错误，创建订单失败");
                    }
                }else{
                    Db::rollback();
                    $this->error("未知错误，创建订单失败");
                }

            }else{
                Db::rollback();
                $this->error("未知错误，交易失败");
            }
            //生成卡密
            for ($i = 0; $i < $cardcount; $i++) {
                $card = array();
                $card['user_id'] = $user['id'];
                $card['card_no'] = strtoupper(md5($this->guuid().time().$user['id'].$i));
                $dayinfo = $this->get_card_time($buycard);
                $card['use_days'] = $dayinfo['days'];
                $card['use_time'] = $dayinfo['time'];
                $card['order_id'] = $orderid;
                $card['create_time'] = time();
                if(!Db::name("cards")->insert($card)){
                    Db::rollback();
                    $this->error("未知错误，卡密生成失败");
                }
            }
            Db::commit();
            $this->success(NULL,"卡密生成成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();//var_dump($e);
            return $this->error('未知错误，卡密生成失败');
        }
    }
    //拥有卡密查询
    public function own_cards(){
        $active = input("active") == 1 ? 1 : 0;
        $cardtype = intval(input("cardtype"));
        $db = Db::name("cards")->where("actived",$active);
        $user = $this->user;

        if($cardtype>0 && $cardtype<=365){
            $db = $db->where("use_days",$cardtype);
        }elseif($cardtype>365){
            $db = $db->where("use_days",'>',365);
        }

        $db = $db->order("id","desc");
        if($user['user_type'] == 'admin'){
            $list = $db->paginate(10);
        }else{
            $list = $db->where("user_id",$user['id'])->paginate(10);
        }

        $list->each(function ($item,$key){
            $item['title'] = $this->getCardTitle($item['use_days'],true);
            $item['use_days'] = $item['use_days']<=365 ? $item['use_days'].'天' : '终身免费';
            $item['active_user'] = $item['actived'] ? Db::name("user")->where("id",$item['active_user'])->value("username") : '';
            $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
            $item['active_time'] = $item['active_time'] ? date('Y-m-d H:i:s',$item['active_time']) : '';
            return $item;
        });
        $this->success($list);
    }

    public function orderlist(){
        $user = $this->user;
        $db = Db::name("orders")->where("type",0);

        $db = $db->order("id","desc");
        if($user['user_type'] == 'admin'){
            $list = $db->paginate(10);
        }else{
            $list = $db->where(function ($query) {
                $query->where("user_id", $this->user['id'])->whereOr("payuser_id", $this->user['id']);
            })->paginate(10);
        }

        $list->each(function ($item,$key){
            if($this->user['user_type'] == 'admin') $item['buyuser'] = Db::name("user")->where("id",$item['user_id'])->value("username");
            $item['need_money'] = number_format($item['need_money'],2);
            $item['payed_money'] = number_format($item['payed_money'],2);
            $item['type'] =  $item['type'] == 1 ? '系统操作' : ($item['type'] == 2 ? '转账支付' : '购买卡密');
            $item['info'] = $item['payuser_id'] == $this->user['id'] ?  '系统调节账户' : $item['info'];
            $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
            $item['payed_time'] = $item['payed_time'] ? date('Y-m-d H:i:s',$item['payed_time']) : '未支付';
            return $item;
        });
        $this->success($list);
    }

    public function getcards(){
        $orderid = intval(input("orderid"));
        $db = Db::name("cards")->where("order_id",$orderid);
        if($this->user['user_type'] != 'admin') $db = $db->where("user_id",$this->user['id']);
        $list = $db->field("card_no,actived")->select();
        $this->success($list);
    }

    public function check(){
        $card = Db::name("cards")->where("card_no",input("card_no"))->find();
        $this->success(NULL,$card && $card['actived'] ? "此卡密已使用" : ($card ? "此卡密还未使用" : "不存在此卡密"));
    }
}
